import {
  SysUIActionTag,
  ViewController,
  ViewEngineBase,
} from '@ibiz-template/runtime';
import { RouteLocationNormalizedLoaded, useRoute } from 'vue-router';
import { IPanelField } from '@ibiz/model-core';
import { PanelFieldController } from '@ibiz-template/vue3-util';
import { notNilEmpty } from 'qx-util';

export class LoginViewEngine extends ViewEngineBase {
  route: RouteLocationNormalizedLoaded = useRoute();

  get AppLoginView(): ViewController {
    return this.view.getController('AppLoginView') as ViewController;
  }

  async onMounted(): Promise<void> {
    super.onMounted();

    // 支持enter登录
    document.addEventListener('keydown', this.enterKeyListener);
  }

  async onDestroyed(): Promise<void> {
    super.onDestroyed();
    // 移除全局事件监听以避免内存泄漏
    document.removeEventListener('keydown', this.enterKeyListener);
  }

  async call(key: string, args: IData = {}): Promise<IData | null | undefined> {
    if (key === SysUIActionTag.LOGIN) {
      await this.login(args);
    }
    if (key === SysUIActionTag.CANCEL_CHANGES) {
      await this.cancelChanges();
    }
    return super.call(key, args);
  }

  async login(args: IData): Promise<void> {
    let rememberme;
    if (
      this.AppLoginView.layoutPanel &&
      typeof this.AppLoginView.layoutPanel.data.isRemember === 'boolean'
    ) {
      rememberme = this.AppLoginView.layoutPanel.data.isRemember;
    }
    const data = args.data[0] || {};
    let username = data.username;
    if (notNilEmpty(data.orgid)) {
      username = `${data.username}@${data.orgid}`;
    }
    const bol = await ibiz.auth.login(username, data.password, rememberme);
    if (bol === true) {
      window.location.hash = (this.route.query.ru as string) || '/';
      window.location.reload();
    }
  }

  async cancelChanges(): Promise<void> {
    if (this.AppLoginView.layoutPanel) {
      Object.keys(this.AppLoginView.layoutPanel.panelItems).forEach(key => {
        const controller = this.AppLoginView.layoutPanel!.panelItems[
          key
        ] as PanelFieldController;
        const { viewFieldName } = controller.model as IPanelField;
        if (viewFieldName) {
          controller.setDataValue('', viewFieldName);
        }
      });
    }
  }

  private enterKeyListener = async (event: KeyboardEvent) => {
    if (event.key === 'Enter' && this.AppLoginView.layoutPanel) {
      const args = {
        data: [
          {
            username: this.AppLoginView.layoutPanel.data.username,
            password: this.AppLoginView.layoutPanel.data.password,
          },
        ],
      };
      await this.login(args);
    }
  };
}
